package com.wms.ymcc.web.controller;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.comm.SignVersion;
import com.wms.ymcc.result.JSONResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author : 阿盛哟
 * @description :
 * @createDate : 2025/6/3 9:40
 */
@RestController
@RequestMapping("/oss")
public class OSSController {

    @PostMapping("/uploadFile")
    public JSONResult uploadFile(@RequestParam MultipartFile fileName) {
        String endpoint = "https://oss-cn-beijing.aliyuncs.com";
        String bucketName = "wms-ymcc";

        // 创建 OSSClient 实例
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        // 显式声明使用 V4 签名算法
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);

        OSS ossClient = new OSSClientBuilder().build(endpoint, "LTAI5tDL3XBaW2u39JtvZpJZ",
                "BnDqafHEYE8vrSEJWtTOMdP0bX5Z7m");
        try {
            // 2. 上传文件， 日期指定路径   2025/05/20    xxyy
            String format = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
            // 文件名不能重复的，时间戳生
            //  获取上传文件的后缀。  yy.aa.bb.xx.mp4
            String originalFilename = fileName.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String objectName = format + "/" + System.currentTimeMillis() + suffix;

            InputStream inputStream = fileName.getInputStream();

            ossClient.putObject(bucketName, objectName, inputStream);
            System.out.println("上传成功");

            // https://cjc-ymcc.oss-cn-hangzhou.aliyuncs.com/2025/05/20/1747743486720.webp
            return JSONResult.success("https://wms-ymcc.oss-cn-beijing.aliyuncs.com/"+objectName);
        } catch (Exception oe) {
            oe.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return JSONResult.error();
    }

    /**
     * 删除接口，自己实现
     */
}